package com.cloudptt.api.product;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.pjsip.api.SipManager;
import com.cloudptt.api.product.func.lbs.AlarmTimer;
import com.cloudptt.api.product.func.lbs.IAlarmTimeout;
import com.cloudptt.api.product.func.lbs.LbsListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.LBSOperator;
import com.cloudptt.api.models.lbs.ReportData;
import com.mcptt.config.body.location.LocationInfoBody;
import com.mcptt.config.body.location.LocationInfoBody_Configuration;
import com.mcptt.config.body.location.LocationInfoBody_Request;
import com.mcptt.db.DBAdapter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class ReportAndKeepLive extends BroadcastReceiver implements IAlarmTimeout {
	public final static String THIS_FILE = "ReportAndKeepLive";

	public final static String TimerOutKey_Clear = "clearData";
	public final static String TimerOutKey_Report = "reportData";

	private static long BaseDate = 0;

	private Context ctx = null;
	private int reportInternal = 5;
	private LBSOperator operator;
	private DBAdapter dpOperator = null;
	private LbsListener listener = null;

	private AlarmTimer reportTimer = null;
	private IGetReportData reportDate = null;
	private volatile boolean isRecvDistribute = false;


	public ReportAndKeepLive(Context ctx, LBSOperator operator, IGetReportData reportDate) {
		this.ctx = ctx;
		this.operator = operator;
		this.reportDate = reportDate;
		BaseDate = System.currentTimeMillis();
		Log.d(THIS_FILE, "GpsLocServer start BaseDate = "+BaseDate);

		ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_REGISTER_TIMEOUT));
		ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_LOCATION));
	}

	public void setListener(LbsListener listener) {
		this.listener = listener;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.d(THIS_FILE, "onReceive:Action is " + action);
		if (SipManager.ACTION_SIP_REGISTER_TIMEOUT.equals(action))
		{
			doTimerOutClear();
		}
		else if (SipManager.ACTION_SIP_LOCATION.equals(action))
		{
			String locationInfoBody = intent.getStringExtra(SipManager.Body_Str);
			Log.i(THIS_FILE, "onReceive: ACTION_SIP_LOCATION locationInfoBody = " + locationInfoBody);
			int bodyType = LocationInfoBody.parseMsgType(locationInfoBody);
			Log.i(THIS_FILE, "onReceive: ACTION_SIP_LOCATION bodyType = " + bodyType);
			if(bodyType == LocationInfoBody.Type_Configuration)
			{
				try {
					LocationInfoBody_Configuration configuration = LocationInfoBody_Configuration.parseXmlStr(locationInfoBody);
					Log.i(THIS_FILE, "onReceive: ACTION_SIP_LOCATION configuration = " + configuration);
					if(reportDate != null)
					{
						reportDate.setTriggerId(configuration.getTriggerId());
					}
					reportInternal = configuration.getTimeInterval();
					startTimer();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
			else if(bodyType == LocationInfoBody.Type_Request)
			{
				try {
					LocationInfoBody_Request request = LocationInfoBody_Request.parseXmlStr(locationInfoBody);
					Log.i(THIS_FILE, "onReceive: ACTION_SIP_LOCATION request = " + request);
					String id = request.getRequestId();
					recvRequest(id);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}

	}

	public void startTimer() {
		Log.d(THIS_FILE, "startTimer reportInternal = " + reportInternal);

		stopTimer();
		doReportDate();
		this.reportTimer = new AlarmTimer(ctx,TimerOutKey_Report,reportInternal,this);
		reportTimer.startRefreshTimer();
	}
	public void stopTimer() {
		Log.d(THIS_FILE, "stopTimer");
		if(reportTimer != null)
		{
			this.reportTimer.stopRefreshTimer();
			this.reportTimer = null;
		}
	}

	public void clearResource() {
		Log.d(THIS_FILE, "LBSBroadcast clearResource");
		if(reportTimer != null)
		{
			this.reportTimer.stopRefreshTimer();
			this.reportTimer = null;
		}
		this.ctx.unregisterReceiver(this);
		this.ctx = null;
		this.listener = null;
	}

	@Override
	public void timeIntervalTimeout(String alarmAction) {
		// TODO Auto-generated method stub
		Log.d(THIS_FILE, "timeIntervalTimeout alarmAction = " + alarmAction);
		if(TimerOutKey_Clear.equals(alarmAction))
		{
			doReportDate();
			doTimerOutClear();
		}
		else if(TimerOutKey_Report.equals(alarmAction))
		{
			doReportDate();
		}
	}

	private void doTimerOutClear()
	{
		Log.i(THIS_FILE, "doTimerOutClear isRecvLbsDistribute = " + isRecvDistribute);
		if(!isRecvDistribute)
		{
			this.dpOperator.cleanAllLogin();

			if(listener != null)
			{
				listener.recvNewReport();
			}
		}
		isRecvDistribute = false;
	}
	public void doReportDate()
	{
		if(operator != null)
		{
			ReportData data = reportDate.getReportData();
//			Log.i(THIS_FILE, "doReportDate data = " + data + " data.isValid() = " + data.isValid());
			if(data != null
				&& data.isValid()) {
				String dataStr = data.toString(false,null);
				int result = operator.reportLocation(dataStr);
				if (result != CauseCont.OperateCheck_Suc
					&& result != CauseCont.OperateCheck_Sys_UnLogin
					&& result != CauseCont.OperateCheck_Sys_SvrStart)
				{
					String errStr = CauseCont.getOperateCheckErrStr(result, ctx);
					CommDlg.showToast(ctx, errStr);
				}
			}
		}
	}



	public void recvRequest(String mcpttId) {
		// TODO Auto-generated method stub
		Log.e(THIS_FILE, " recvRequest mcpttId = " + mcpttId);

		if(operator != null)
		{
			ReportData data = reportDate.getReportData();
			if(data != null
				&& data.isValid()) {
				String dataStr = data.toString(true,mcpttId);
				int result = operator.reportLocation(dataStr);
				if (result != CauseCont.OperateCheck_Suc) {
					String errStr = CauseCont.getOperateCheckErrStr(result, ctx);
					CommDlg.showToast(ctx, errStr);
				}
			}
		}
	}

	public void recvConfiguration(String mcpttId, LocationInfoBody_Configuration body) {
		// TODO Auto-generated method stub
		Log.e(THIS_FILE, " recvConfiguration mcpttId = " + mcpttId + " body = " + body);
//		if(localConfig != null
//				&& mcpttId != null)
//		{
////			localConfig.updateConfig(mcpttId,body);
//			//lbs.updateConfig(ctx, mcpttId, localConfig);
//		}
	}
}
